import { Spin } from 'antd';
import { FC, useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import './index.less';

import FlawCards from './component/flaw-card';
import LotHeadInfo from './component/lot-head-info';
import SheetFlawMap from './component/sheet-flaw-map';
import SheetTable from './component/sheet-table';
import CardDetailDialog from '@/components/FlawDetailDialog';
import { useStores } from '@/stores';
import LotFlawMap from './component/lot-flaw-map';
import { EchartFlawMapT, flawMapT } from '@/typings/global';
import { runInAction } from 'mobx';
import { XandYAxisT } from './type';
import { merageDotInfo } from '../synthesize-map/script/tool';
import { handleFlawTypeParams, handleLotHead } from '../split-roll/script/tool';
import { getLotFlawMapBack, getLotHeadInfoBack } from '@/api/lot-detail-page';
import { LOT_HEAD_LABEL_OBJ, UNIT_TO_M } from '@/utils/constant';
import { getEchartAxis, MessageWaring } from '@/utils/tool';


const detailSlitPage: FC = () => {
  const { lotStore, commonStore } = useStores();
  const [spinState, setSpinState] = useState<boolean>(false);
  const location = useLocation();
  const { pathname } = location;
  const lotId = pathname.slice(8);

  const chartsRef = useRef<any>(null);
  const sheetRef = useRef<any>(null);
  const lotHeadRef = useRef<any>(null);
  const sheetTableRef = useRef<any>(null);
  const flawCardRef = useRef<any>(null);

  useEffect(() => {
    console.log('卷详情——--location', location);
    if (lotId && lotId.trim()) {
      initReuest();
    } else {
      MessageWaring('分条号lotId不存在!');
    }
  }, []);

  // 初始化请求
  const initReuest = async () => {
    console.log('这是卷详情大页面，初始化的请求喽');
    setSpinState(true);
    lotStore.lotId = lotId.trim();
    const headInfo = await requestLotHeadInfo(lotId);
    if (!headInfo || Object.keys(headInfo).length === 0) {
      setSpinState(false);
      return;
    }
    const { layerId } = headInfo;
    if (!layerId) {
      MessageWaring('分条号对应的前道卷批号不存在!');
      setSpinState(false);
      return;
    }
    lotStore.layerId = layerId;
    const lotOptMinMax = getEchartAxis(flawMapT.lot, headInfo.x, headInfo.y, headInfo.lotWidth, headInfo.lotHeight,headInfo.qrMd);
    console.log('小卷的信息:', lotOptMinMax);
    initReqLotMap(layerId, lotOptMinMax);
    initReqSheetList(lotId, commonStore, lotStore);
  };

  // 初始化请求小卷的缺陷地图
  const initReqLotMap = async (layerId: string, lotOptMinMax: XandYAxisT) => {
    await requestLotMapData(layerId, lotId, commonStore, lotOptMinMax);
    setSpinState(false); // 停止loading
  };

  // 初始化请求片列表
  const initReqSheetList = async (lotId: string, commonStore, lotStore) => {
    // 1 [中-左] sheet列表
    // 2 [中-右] 片的缺陷地图 sheet=1 一个片下面的缺陷地图
    // 3 [右] 缺陷卡片 sheet = 1 一个片下面的缺陷卡片
    await lotStore.changeSheetListReq(lotId, commonStore);
    chartsRef?.current?.changeOption({ seriesData: lotStore.lotFlawSeriesData });
  };

  /**[ 左侧 ]
   * 请求卷--缺陷地图的缺陷数据
   * @param layerId
   * @param lotId
   * @param commonStore
   */
  const requestLotMapData = async (layerId: string, lotId: string, commonStore, lotOptMinMax: XandYAxisT) => {
    try {
      const newParams = handleFlawTypeParams(lotStore, commonStore, { lotId: lotId, layerId: layerId });
      const resBack = await getLotFlawMapBack(newParams);
      runInAction(() => {
        // 处理缺陷地图的数据，赋值option
        lotStore.lotFlawSeriesData = merageDotInfo(resBack.flawList, commonStore);
        if (lotOptMinMax) {
          // 如果是改变缺陷筛选后，则不会传递这个值，从而延续之前的lot的最值
          lotStore.lotOptMinMax = lotOptMinMax;
        }
      });
    } catch (error) {
      console.log('error', error);
    }
  };

  /**[ 中间-上 ]
   * 小卷lotId的头部信息
   * @param layerId
   * @param lotId
   */
  const requestLotHeadInfo = async (lotId: string) => {
    try {
      const resBack = await getLotHeadInfoBack({ lotId: lotId });
      // 需要更改将下面的LotHeadInfoBack-》resBack.data
      runInAction(() => {
        lotStore.lotHeadInfo = handleLotHead({ ...resBack, layerId: resBack.layerId ? resBack.layerId : '' }, LOT_HEAD_LABEL_OBJ);
      });
      return resBack;
    } catch (error) {
      console.log('error', error);
      return {};
    }
  };

  /**
   * 点击片列表中的某一行
   * @param sheetInfo
   */
  const activeSheet = sheetInfo => {
    runInAction(() => {
      lotStore.sheet.sheetId = sheetInfo.sheetId;
      //更新对应分条sheet在分卷中的红线高度显示
      lotStore.sheet.headMd = sheetInfo.doffMd ? sheetInfo.doffMd / UNIT_TO_M : 0;
    });
    //更新对应的sheetMap的缺陷点
    lotStore.changeSheetFlawMapReq(sheetInfo.sheetId, commonStore);
    //更新对应的sheet的缺陷卡片列表
    lotStore.changeFlawCardReq(sheetInfo.sheetId, lotStore.lotId);
  };

  return (
    <>
      <div>
        <Spin size="large" tip="加载中..." spinning={spinState}>
          <div className="lot-detail">
            <LotFlawMap onRef={chartsRef} type={EchartFlawMapT.lotFlawMap}></LotFlawMap>
            <div className="mid-content">
              <LotHeadInfo onRef={lotHeadRef} reRender={initReuest}></LotHeadInfo>
              <div className="mid-sheet">
                <SheetTable onRef={sheetTableRef} onSubmit={activeSheet}></SheetTable>
                <SheetFlawMap onRef={sheetRef}></SheetFlawMap>
              </div>
            </div>
            <FlawCards onRef={flawCardRef}></FlawCards>
            <CardDetailDialog></CardDetailDialog>
          </div>
        </Spin>
      </div>
    </>
  );
};

export default detailSlitPage;
